package com.ybg.bookmanages.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybg.bookcommons.dto.ReturnDTO;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class TokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate template;

    public TokenInterceptor(StringRedisTemplate srt){
        this.template = srt;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ObjectMapper om = new ObjectMapper();
        //1.获取请求头中的Authorization
        String auth = request.getHeader("Authorization");
        //2.无法获取token token为null 说明用户尚未登录
        if(auth == null){
            //准备提示前端用户 发生错误
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            ReturnDTO rdto = ReturnDTO.builder().status("fail").message("用户尚未登录").build();
            out.write(om.writeValueAsString(rdto));
            out.flush();
            out.close();
            return false;
        }
        //3.用户有令牌但是超期限 结果有问题
        String res = template.opsForValue().get(auth);
        if(res==null) {
            //中文乱码处理
            response.setCharacterEncoding("UTF-8");
            //调用输出流输出错误
            PrintWriter out = response.getWriter();
            ReturnDTO rdto = ReturnDTO.builder().status("fail").message("用户登录超时,请重新登录").build();
            out.write(om.writeValueAsString(rdto));
            out.flush();
            out.close();
            return false;
        }

        return true;
    }
}
